//
//  TopicDetailViewController.swift
//  HoneyBee
//
//  Created by Smith_Yang on 2018/4/29.
//  Copyright © 2018 point. All rights reserved.
//

import UIKit
import MJRefresh
import AVKit


private let kHeadCell = "HeadCell"
private let kContentCell = "ContentCell"
private let kButtonCell = "ButtonCell"
private let kCommentCell = "CommentCell"
private let kVideoCell = "VideoCell"

class TopicDetailViewController: BaseViewController {
    
    @IBOutlet weak var tableViewTopLayout: NSLayoutConstraint!
    fileprivate var topicDetailModel: TopicDetailModel?
    fileprivate var heightContent: CGFloat = 44
    fileprivate var commentsModels: [TopicCommentModel] = [TopicCommentModel]()
    var modelID = 0
    fileprivate var hasMore = true
    fileprivate var pageNo = 1;
    
    var commentId = 0;
    var replyUserId = 0;
    
    var isClickBtn = false;
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var inputTextField: UITextField!
    @IBOutlet weak var inputBarView: UIView!
    @IBOutlet weak var starButton: UIButton!
    @IBOutlet weak var shareButton: UIButton!
    @IBOutlet weak var commentButton: UIButton!
    
    @IBOutlet weak var inputBarMarginConstraint: NSLayoutConstraint!
    var childVC = AVPlayerViewController.init()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.setupUI()
        
       // NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)),name:NSNotification.Name.UIKeyboardWillHide, object: nil)
       // NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)),name:NSNotification.Name.UIKeyboardWillShow, object: nil)
        
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
//
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        tableViewTopLayout.constant = self.navgationBar.height;
    }
    
    deinit {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    public func configModel(model:TopicModel){
        
        modelID = model.id
        
        self.loadModelData()
        
    }
    
    func loadModelData() {
        
        self.hudLoad()
        
        let dict = [
            "id": modelID,
            "userId":String(UserInfo.shareInstance.userModel().id)] as [String : Any]
        
        TempNetTool.post( kHost + kqueryTopicInfo + "".apiF(time: "2", sign: "2") + "&id=\(modelID)", parameters: dict, progress: nil, success: { [weak self] (result) in
            
            self?.hudHide()
            
            if (result != nil) {
                guard let resultDict = result as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [String : NSObject] else { return }
                let detailModel = TopicDetailModel.tmSpeelBreak(dataArray)
                self?.topicDetailModel = detailModel
                
                self?.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
                    self?.loadData()
                })
                self?.tableView.mj_footer.beginRefreshing()
                
                self?.setupInputView()
                self?.tableView.reloadData()
            }
            
            
        }) {[weak self]   (error) in
            self?.hudHide()
            self?.tableView.mj_footer.endRefreshing()
            
        }
        
    }
    
    func focusAuthor(_ isSelected : Bool){
        
        guard let topicModel = topicDetailModel else {return}
        
        self.hudLoad()
        
        let dict = [
            "concernUserId": String(topicModel.authorId),
            "isDelete": isSelected,
            "userId":String(UserInfo.shareInstance.userModel().id)] as [String : Any]
        
        TempNetTool.post( kHost + kconcernAuthor + "".apiF(time: "1", sign: "dd") + "&isDelete=\(isSelected)" + "&concernUserId=\(topicModel.authorId)", parameters: dict, progress: nil, success: { [weak self] (result) in
            
            self?.hudHide()
            guard let resultDict = result as? [String : NSObject] else { return }
            
            if (resultDict["resCode"] as! String == "200") {
                self?.loadModelData()
            }
            
        }) {[weak self]   (error) in
            self?.hudHide()
        }
        
    }
    func setupInputView() {
        
        
        let replayImg = UIImage.icon(from: kIcon_replay, color: kColorTextPlacehold, imageSize: CGSize(width: 15, height: 15)).withRenderingMode(.alwaysOriginal)
        let shareImg = UIImage.icon(from: kIcon_share, color: kColorTextPlacehold, imageSize: CGSize(width: 16, height: 16)).withRenderingMode(.alwaysOriginal)

        let isCollection = self.topicDetailModel?.collection
        changeButtonStatus(isCollection!)
        
        starButton.backgroundColor = UIColor.clear
        starButton.addTarget(self, action: #selector(favoritesAction), for: .touchUpInside)
        commentButton.setImage(replayImg, for: .normal)
        commentButton.backgroundColor = UIColor.clear
        commentButton.addTarget(self, action: #selector(commentAction), for: .touchUpInside)

        shareButton.setImage(shareImg, for: .normal)
        shareButton.backgroundColor = UIColor.clear
        shareButton.addTarget(self, action: #selector(shareAction), for: .touchUpInside)

        
        inputTextField.layer.cornerRadius = inputTextField.frame.size.height/2.0
        
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 30))
        inputTextField.leftView = leftView
        inputTextField.leftViewMode = .always
        inputTextField.delegate = self
        inputTextField.returnKeyType = .send
    }
    
    func changeButtonStatus(_ isSelected:Bool) {
        if (isSelected){
            let favoritesImg = UIImage.icon(from: kIcon_favorites, color: kColorFocusBG, imageSize: CGSize(width: 15, height: 15)).withRenderingMode(.alwaysOriginal)
            starButton.setImage(favoritesImg, for: .normal)
            
        } else {
            let favoritesImg = UIImage.icon(from: kIcon_favorites, color: kColorTextPlacehold, imageSize: CGSize(width: 15, height: 15)).withRenderingMode(.alwaysOriginal)
            starButton.setImage(favoritesImg, for: .normal)
        }
    }
    
    
    @objc func favoritesAction(){
        
        guard let detailModel = self.topicDetailModel else { return }
        if detailModel.collection {
            cancelCollectionTopic()
        } else {
            addCollectionTopic()
        }
        
    }
    
    @objc func commentAction(){
        self.isClickBtn = true
        self.commentId = 0
        self.replyUserId = topicDetailModel?.userId ?? 0
        inputTextField.becomeFirstResponder()
    }
    
    @objc func shareAction(){
        
    }
    
    
    @objc func keyboardWillShow(_ sender: Notification) {
        //获取键盘的frame
        guard let keyboardFrame = (sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {
            return
        }
        //如果边框=0也返回
        if(keyboardFrame == CGRect.zero || keyboardFrame.height == 0){return;}
        UIView.animate(withDuration: 0.1, animations: {
            self.inputBarMarginConstraint.constant = keyboardFrame.height
        })
    }
    
    @objc func keyboardWillHide(_ sender: Notification) {
        UIView.animate(withDuration: 0.1, animations: {
            self.inputBarMarginConstraint.constant = 0
        })
    }

}


// MARK:- TableView Delegate

extension TopicDetailViewController:UITableViewDataSource,UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        guard self.topicDetailModel != nil else {return 0}
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard self.topicDetailModel != nil else {return 0}
        if section == 0 {
            return 3
        }
        else {
            return self.commentsModels.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if  indexPath.section == 0 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: kHeadCell, for: indexPath) as! TopicHeaderTableViewCell
                
                if let detailModel = self.topicDetailModel {
                    cell.configModel(model: detailModel)
                    cell.vc = self;
                }
                
                cell.blockFocus = {(isSelected)->() in
                    
                    self.focusAuthor(isSelected)
                    
                }
                
                return cell
            }else if(indexPath.row == 1) {
                if (self.topicDetailModel?.type == "00"){
                    let cell = tableView.dequeueReusableCell(withIdentifier: kContentCell, for: indexPath) as! TopicContentTableViewCell
                    if let detailModel = self.topicDetailModel {
                        cell.configModel(model: detailModel)
                        cell.changeHeight = {
                            (height) -> Void in
                            self.heightContent = height
                            self.tableView.reloadRows(at: [indexPath], with: .automatic)
                        }
                    }
                    return cell
                } else {
                    let cell = tableView.dequeueReusableCell(withIdentifier: kVideoCell, for: indexPath) as! TopicBannerTableViewCell
                    if let detailModel = self.topicDetailModel {
                        cell.configModel(model: detailModel)
                    }
                    cell.delegate = self
                    return cell
                }
                
            }else if(indexPath.row == 2) {
                let cell = tableView.dequeueReusableCell(withIdentifier: kButtonCell, for: indexPath) as! TopicButtonTableViewCell
                if let detailModel = self.topicDetailModel {
                    cell.configModel(_model: detailModel)
                }
                
                cell.buttonTapBlock = { (model) -> Void in
                    
                    let QRView = TopicAuthorQrImageView()
                    self.view.addSubview(QRView)
                    QRView.configModel(_model: model)
                    QRView.snp.makeConstraints({ (make) in
                        make.left.equalToSuperview()
                        make.top.equalToSuperview()
                        make.bottom.equalToSuperview()
                        make.right.equalToSuperview()
                    })
                    
                }
                
                return cell
            }
        } else if indexPath.section == 1  {
            let cell = tableView.dequeueReusableCell(withIdentifier: kCommentCell, for: indexPath) as! TopicCommentTableViewCell
            
            weak var weakSelf = self;
            cell.configModel(model: self.commentsModels[indexPath.row]) { (btn) in
                 self.isClickBtn = true
                self.commentId = self.commentsModels[indexPath.row].id
                self.replyUserId = self.commentsModels[indexPath.row].userId
                self.inputTextField.becomeFirstResponder()
            }
            return cell

        }
        
        return UITableViewCell()
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if(indexPath.row == 1 && indexPath.section == 0) {
            //return 330
            if (self.topicDetailModel?.type == "00"){
                return self.heightContent

            } else {
                return 330
            }
        } else if (indexPath.row == 2){
            if let detailModel = self.topicDetailModel {
                if (detailModel.topicAuthorAccountModel.count > 0){
                    return UITableView.automaticDimension
                }
            }
            return 0
        }
        else{
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            let header = UIView()
            header.backgroundColor = UIColor.white
            let title = UILabel()
            title.font = UIFont(name: "PingFang-SC-Bold", size: 14)
            title.textColor = UIColor.black
            header.addSubview(title)
            title.translatesAutoresizingMaskIntoConstraints = false
            if self.commentsModels.count == 0 {
                title.text = "暂无评论，快来写下您的想法吧！"
                title.snp.makeConstraints { (make) in
                    make.centerX.equalTo(header.snp.centerX)
                    make.centerY.equalTo(header.snp.centerY)
                }
            }else {
                let line = UIView()
                line.backgroundColor = UIColor(hex: "#f4f4f4")
                header.addSubview(line)
                title.text = "全部评论"
                line.snp.makeConstraints { (make) in
                    make.leading.equalTo(header.snp.leading)
                    make.trailing.equalTo(header.snp.trailing)
                    make.top.equalTo(header.snp.top)
                    make.height.equalTo(3)
                }
                title.snp.makeConstraints { (make) in
                    make.leading.equalTo(header.snp.leading).offset(15)
                    make.top.equalTo(line.snp.bottom).offset(1)
                }
            }
            return header
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            if self.commentsModels.count == 0 {
                return 200
            }else {
                return 30
            }
        } else {
            return 0
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated);
        childVC.player?.pause()
    }
    
}


// MARK:- 设置UI
extension TopicDetailViewController {
    fileprivate func setupUI(){
        self.title = "文章详情"
        tableView.register(UINib(nibName: "TopicHeaderTableViewCell", bundle: nil), forCellReuseIdentifier: kHeadCell)
        tableView.register(UINib(nibName: "TopicContentTableViewCell", bundle: nil), forCellReuseIdentifier: kContentCell)
        tableView.register(UINib(nibName: "TopicButtonTableViewCell", bundle: nil), forCellReuseIdentifier: kButtonCell)
        tableView.register(UINib(nibName: "TopicCommentTableViewCell", bundle: nil), forCellReuseIdentifier: kCommentCell)
        tableView.register(TopicBannerTableViewCell.self, forCellReuseIdentifier: kVideoCell)
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.white
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        tableView.tableFooterView = UIView(frame: CGRect.zero);
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: LayoutCommon.navHeight).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        
        inputBarMarginConstraint.constant = 0
        
        
    }
    
    fileprivate func loadData() {
        guard hasMore else {return};
        guard let topicId = self.topicDetailModel?.id else {return}
        self.hudLoad()
        
        let dict:Dictionary = [
            "timestamp":"2",
            "id":topicId,
            "pageNo": String.init(pageNo),
            "pageSize":"10",
            "sign":"2"
            ] as [String : Any]
        
        let str = dict.formatApi()
        NetworkTools.shareInstance.loadData(MethodType.get, URLString: kqueryCommentOfTopic+str, parameters: dict) { (data, isResult) in
            if !isResult {
                self.hudHide()
                self.tableView.mj_footer.endRefreshing()
                guard let resultDict = data as? [String : NSObject] else { return }
                guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
                let commentList = TopicCommentModel.tmSpeelBreakModelArr(dataArray)
                if commentList.count != 0 {
                    self.commentsModels.append(contentsOf: commentList as! [TopicCommentModel])
                    self.hasMore = true
                    self.tableView.reloadSections([1], with: .automatic)
                    self.pageNo += 1
                } else {
                    self.hasMore = false
                    self.tableView.mj_footer.endRefreshingWithNoMoreData();
                }
            }else{
                self.pageNo = 1
                self.commentsModels.removeAll()
                self.hasMore = false
            }
        }
    }
    
    fileprivate func addCollectionTopic() {
        
        guard let topicId = self.topicDetailModel?.id else {return}
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "id":String(topicId)] as [String : Any]
        
        TempNetTool.post( kHost + kaddCollectTopicList + "".apiF(time: "1", sign: "dd") + "&id=\(topicId)", parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.hudHide()
            
            if (result != nil) {
                self?.loadModelData()
                self?.changeButtonStatus(true)
            }
            
        }) {[weak self]   (error) in
            self?.hudHide()
        }
    }
    
    fileprivate func cancelCollectionTopic() {
        
        guard let topicId = self.topicDetailModel?.id else {return}
        self.hudLoad()
        
        let dict = [
            "userId":String(UserInfo.shareInstance.userModel().id),
            "id":String(topicId)] as [String : Any]
        
        TempNetTool.post( kHost + kcancelCollectTopicList + "".apiF(time: "1", sign: "dd") + "&id=\(topicId)", parameters: dict, progress: nil, success: { [weak self] (result) in
            self?.hudHide()
            
            if (result != nil) {
                self?.loadModelData()
                self?.changeButtonStatus(false)
            }
            
        }) {[weak self]   (error) in
            self?.hudHide()
        }
    }
    
    fileprivate func commentTopic(){
        
//        var dict = [
//            "content":contentTextView.text,
//            "institutionId":schoolID,
//            "userId":String(UserInfo.shareInstance.userModel().id)
//            ] as [String : Any]
//
//        var resourceArr:[[String:Any]] =  [[String:Any]]()
//        for val in tempUploadImgArr {
//            let dict = [
//                "path":val,
//                "fileType":0
//                ] as [String : Any]
//            resourceArr.append(dict)
//        }
//        if resourceArr.count > 0 {
//            dict["resource"] = resourceArr
//        }
//        let api = kHost + kaddCommentInstitution + String().apiF(time: "111", sign: "222")
//
//        TempNetTool.post(api, parameters: dict, progress: nil, success: { [weak self](result) in
//            self?.hudHide()
//            self?.hudLoadMessage("评论成功")
//            self?.backBlock!()
//            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
//                self?.navigationController?.popViewController(animated: true)
//
//            }
//        }) { [weak self](error) in
//            self?.hudError()
//        }
    }

}

// MARK: - 点击显示图片
extension TopicDetailViewController :  TopicBannerTableViewCellDelegate,UITextFieldDelegate {
    func bannerCycleViewDidScrollToIndex(_ index: Int, view : ZCycleView) {
        let vc = self.childVC;
        vc.player = AVPlayer.init(url: URL.init(string: (self.topicDetailModel?.resource)!)!)
        vc.view.frame = view.bounds
        view.addSubview(vc.view)
        vc.player?.play()
        addChild(vc);
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.text?.count  != 0 {
            let dict = [
                "timestamp" : 1,
                "operatorId" : String(UserInfo.shareInstance.userModel().id),
            "sign" : 1] as [String : Any]
            let string = dict.formatApi()
            
            
            let paramers = self.commentId == 0 ?
                ["reply" : textField.text!,
                 "replyUserId" : topicDetailModel?.authorId,
                 "topicId" : topicDetailModel?.id,
            "userId" : String(UserInfo.shareInstance.userModel().id)] as [String : Any]
            
            :  ["reply" : textField.text,
            "replyId" : commentId,
            "replyUserId" : replyUserId,
            "topicId" : topicDetailModel?.id,
            "userId" : String(UserInfo.shareInstance.userModel().id)] as [String : Any]
            
            TempNetTool.post(kHost + kaddReplyOfTopic + string, parameters: paramers, progress: nil, success: {[weak self] (response) in
                let response1 = response as! [String : Any]
                let dict = response1["data"] as! [String : Any]
                self?.hudLoadMessage("评论成功");
                self?.inputTextField.text = ""
                self?.inputTextField.endEditing(true)
                if self?.commentId == 0 {return};
                let topic = TopicCommentModel.init()
                topic.userId = UserInfo.shareInstance.userModel().id
                topic.userName = UserInfo.shareInstance.userModel().userName
                topic.headImg = UserInfo.shareInstance.userModel().headImg
                topic.reply = dict["reply"] as! String
                topic.createTime = String.init(Int(NSDate().timeIntervalSince1970 * 1000))
                self?.commentsModels.append(topic)
                self?.tableView.reloadSections(IndexSet.init(integer: 1), with: .none)
            }) { (error) in
                
            }
        }
        
        return true
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return self.isClickBtn
    }
    
}

